from django.shortcuts import render

# Create your views here.
# from fdfs_client.client import Fdfs_client
# client = Fdfs_client('utils/fdfs/client.conf')
# client.upload_by_filename('/home/python/Desktop/123.jpg')
from rest_framework.generics import ListAPIView
from rest_framework.response import Response
from rest_framework.views import APIView

from goods.models import SKU
from goods.serialziers import HotSerializer, OrderGoodCommentSerializer
from order.models import OrderGoods, OrderInfo


class HotSKUAPIView(ListAPIView):
    pagination_class = None
    serializer_class = HotSerializer

    # queryset = SKU.objects.all()
    # queryset = SKU.objects.filter(category_id=category_id).order_by('-sales')[:2]

    def get_queryset(self):
        category_id = self.kwargs['category_id']

        return SKU.objects.filter(category_id=category_id).order_by('-sales')[:2]




from rest_framework.filters import OrderingFilter
from rest_framework.pagination import LimitOffsetPagination,PageNumberPagination

# class CustomPageNumberPagination(PageNumberPagination):
#
#     page_size = 2
#     page_size_query_param = 'page_size'
    # pass


class SKUAPIView(ListAPIView):

    serializer_class = HotSerializer

    # 添加排序
    filter_backends = [OrderingFilter]
    ordering_fields =['sales','price','create_time']

    # 添加分页
    # page=4            第几页
    # page_size=100     每页多少条
    # pagination_class = CustomPageNumberPagination

    def get_queryset(self):
        category_id = self.kwargs['category_id']

        # SKU.objects.filter(category=xxx)
        return SKU.objects.filter(category_id=category_id)

from .serialziers import SKUIndexSerializer
from drf_haystack.viewsets import HaystackViewSet

class SKUSearchViewSet(HaystackViewSet):
    """
    SKU搜索
    """
    index_models = [SKU]

    serializer_class = SKUIndexSerializer


class DetailGoodsCommentAPIView(APIView):
    """
    商品详情页评论展示
    """

    def get(self, request, sku_id):
        # 从数据库中查询评论信息, 获得评论列表查询集
        ordergoods = OrderGoods.objects.filter(sku_id=sku_id, is_commented=True).order_by('create_time')

        # 创建序列化器
        serializer = OrderGoodCommentSerializer(instance=ordergoods, many=True)

        # 获取字典数据
        commnets = []


        for commnet_score in serializer.data:
            data = {}
            data['comment'] = commnet_score['comment']
            data['score'] = commnet_score['score']
            order_id = commnet_score['order_id']
            user = OrderInfo.objects.get(pk=order_id).user   # user 对象
            data['username'] = user.username

            commnets.append(data)

        # 返回响应 comment score username
        return Response(data=commnets)